import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '../views/home/Home')
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: "shop" */ '../views/shop/Shop')
  },
  {
    path: '/Login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login/Login'),
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage// 如果已经登陆了禁止回到登陆页
      isLogin ? next({ name: 'Home' }) : next()// 代码简化
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "register" */ '../views/register/Register'),
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage// 如果已经登陆了禁止回到登陆页
      isLogin ? next({ name: 'Home' }) : next()// 代码简化
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 实现登陆才能访问功能
router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage
  const { name } = to
  const isLoginOrRegister = (name === 'Login' || name === 'Register');
  (isLogin || isLoginOrRegister) ? next() : next({ name: 'Login' })
})
export default router
